"""
Login management module for HeyGen video generator.
Handles user authentication and session verification.
"""

import sys
import os

# Add the project root directory to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from playwright.async_api import Page, TimeoutError


class LoginManager:
    """
    Manages user login and session verification for HeyGen.
    """
    
    def __init__(self, email: str, password: str):
        """
        Initialize LoginManager.
        
        Args:
            email (str): User email for login
            password (str): User password for login
        """
        self.email = email
        self.password = password
    
    async def is_logged_in(self, page: Page) -> bool:
        """
        Check if user is already logged in.
        
        Args:
            page (Page): Playwright page instance
            
        Returns:
            bool: True if user is logged in, False otherwise
        """
        try:
            # Check if Create button exists (indicates logged in state)
            await page.wait_for_selector("button:has-text('Create')", timeout=5000)
            return True
        except TimeoutError:
            return False
    
    async def login(self, page: Page) -> bool:
        """
        Perform login to HeyGen account.
        
        Args:
            page (Page): Playwright page instance
            
        Returns:
            bool: True if login successful, False otherwise
        """
        print("Logging in...")
        try:
            # Wait for email input field
            await page.wait_for_selector("input[type='email']", timeout=10000)
            print("Email input found")
            
            # Fill email
            await page.fill("input[type='email']", self.email)
            print("Email filled")
            
            # Click Continue button
            await page.click("button:has-text('Continue')")
            print("Continue button clicked")
            
            # Wait for password input field
            await page.wait_for_selector("input[type='password']", timeout=10000)
            print("Password input found")
            
            # Fill password
            await page.fill("input[type='password']", self.password)
            print("Password filled")
            
            # Click Log In button
            await page.click("button:has-text('Log In')")
            print("Login button clicked")
            
            # Wait for login completion
            await page.wait_for_selector("button:has-text('Create')", timeout=20000)
            print("Login successful")
            return True
            
        except Exception as e:
            print(f"Login failed: {e}")
            return False
    
    async def close_welcome_dialog(self, page: Page):
        """
        Close welcome dialog if it appears after login.
        
        Args:
            page (Page): Playwright page instance
        """
        try:
            await page.wait_for_selector("img[alt='Close']", timeout=2000)
            close_button = await page.query_selector("img[alt='Close']")
            if close_button:
                await close_button.click()
                await page.wait_for_timeout(1000)
                print("Closed welcome dialog")
        except Exception as e:
            print(f"No welcome dialog to close: {e}")